@extends('layouts.app')

@section('title', '记账')

@section('content')
    <div class="page-header">
        <button class="back-btn" onclick="window.location.href = '/'">‹</button>
        <h1 class="page-title">记账</h1>
    </div>
    <div class="form-container">
        <div class="record-type-tabs">
            <div class="record-type-tab expense {{ $type === 'expense' ? 'active' : '' }}" id="expense-tab">支出</div>
            <div class="record-type-tab income {{ $type === 'income' ? 'active' : '' }}" id="income-tab">收入</div>
        </div>

        <form id="transaction-form">
            @csrf
            <input type="hidden" id="transaction-type" name="type" value="{{ $type }}">
            <input type="hidden" id="record-date" name="transaction_date" value="{{ $transaction_date ?: date('Y-m-d') }}">
            <div class="form-group">
                <label class="form-label">分类</label>

                <!-- 支出分类 -->
                <div class="category-selector" id="expense-categories" style="{{ $type === 'expense' ? 'display: grid' : 'display: none' }}">
                    @if(count($expenseCategories) > 0)
                        @foreach($expenseCategories as $index => $cat)
                        <div class="category-item {{ $category == $cat->id && $type === 'expense' ? 'active' : '' }}" data-category="{{ $cat->name }}" data-category-id="{{ $cat->id }}" data-type="expense">
                            <div class="category-icon">{{ $cat->icon }}</div>
                            <div class="category-name">{{ $cat->name }}</div>
                        </div>
                        @endforeach
                    @else
                        <div style="grid-column: 1 / -1; text-align: center; color: #999;">暂无支出分类</div>
                    @endif
                </div>

                <!-- 收入分类 -->
                <div class="category-selector" id="income-categories" style="{{ $type === 'income' ? 'display: grid' : 'display: none' }}">
                    @if(count($incomeCategories) > 0)
                        @foreach($incomeCategories as $index => $cat)
                        <div class="category-item {{ $category == $cat->id && $type === 'income' ? 'active' : '' }}" data-category="{{ $cat->name }}" data-category-id="{{ $cat->id }}" data-type="income">
                            <div class="category-icon">{{ $cat->icon }}</div>
                            <div class="category-name">{{ $cat->name }}</div>
                        </div>
                        @endforeach
                    @else
                        <div style="grid-column: 1 / -1; text-align: center; color: #999;">暂无收入分类</div>
                    @endif
                </div>

                <!-- 支出二级分类 -->
                @foreach($expenseCategories as $cat)
                @if($cat->subCategories->count() > 0)
                <div class="subcategory-selector" id="subcategory-expense-{{ $cat->id }}" style="{{ $category == $cat->id && $type === 'expense' ? 'display: block' : 'display: none' }}">
                    <div class="subcategory-title">{{ $cat->name }} - 二级分类</div>
                    <div class="subcategory-box">
                        @foreach($cat->subCategories as $subCat)
                            <div class="subcategory-item {{ $sub_category == $subCat->id ? 'active' : '' }}" data-subcategory="{{ $subCat->name }}" data-subcategory-id="{{ $subCat->id }}">
                                <div class="subcategory-icon">{{ $subCat->icon }}</div>
                                <div class="subcategory-name">{{ $subCat->name }}</div>
                            </div>
                        @endforeach
                    </div>
                </div>
                @endif
                @endforeach

                <!-- 收入二级分类 -->
                @foreach($incomeCategories as $cat)
                @if($cat->subCategories->count() > 0)
                <div class="subcategory-selector" id="subcategory-income-{{ $cat->id }}" style="{{ $category == $cat->id && $type === 'income' ? 'display: block' : 'display: none' }}">
                    <div class="subcategory-title">{{ $cat->name }} - 二级分类</div>
                    <div class="subcategory-box">
                    @foreach($cat->subCategories as $subCat)
                    <div class="subcategory-item {{ $sub_category == $subCat->id ? 'active' : '' }}" data-subcategory="{{ $subCat->name }}" data-subcategory-id="{{ $subCat->id }}">
                        <div class="subcategory-icon">{{ $subCat->icon }}</div>
                        <div class="subcategory-name">{{ $subCat->name }}</div>
                    </div>
                    @endforeach
                    </div>
                </div>
                @endif
                @endforeach

                <div class="category-selected-info" id="category-selected-info"></div>
            </div>


            <!-- 输入区域 -->
            <div class="input-area">
                <input type="text" class="description-input" id="record-note" name="description" placeholder="添加备注..." value="{{ $note }}">
                <div class="amount-display" id="amount-display">{{ $amount ?: '0.00' }}</div>
                <button type="button" class="receipt-upload" id="receipt-upload">📷</button>
            </div>

            <!-- 计算器 -->
            <div class="calculator">
                <div class="calculator-grid">
                    <button type="button" class="calculator-btn" data-value="7">7</button>
                    <button type="button" class="calculator-btn" data-value="8">8</button>
                    <button type="button" class="calculator-btn" data-value="9">9</button>
                    <button type="button" class="calculator-btn date" id="date-btn">📅 <span id="date-display"></span></button>
                    <button type="button" class="calculator-btn" data-value="4">4</button>
                    <button type="button" class="calculator-btn" data-value="5">5</button>
                    <button type="button" class="calculator-btn" data-value="6">6</button>
                    <button type="button" class="calculator-btn operator" data-value="+">+</button>

                    <button type="button" class="calculator-btn" data-value="1">1</button>
                    <button type="button" class="calculator-btn" data-value="2">2</button>
                    <button type="button" class="calculator-btn" data-value="3">3</button>
                    <button type="button" class="calculator-btn operator" data-value="-">-</button>

                    <button type="button" class="calculator-btn" data-value="0">0</button>
                    <button type="button" class="calculator-btn" data-value=".">.</button>
                    <button type="button" class="calculator-btn" id="delete-btn">⌫</button>
                    <button type="button" class="calculator-btn operator" id="saveBtn">完成</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 日期选择模态框 -->
    <div class="modal fade" id="dateModal" tabindex="-1" role="dialog" aria-labelledby="dateModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content modal-test">
                <div class="modal-header">
                    <h5 class="modal-title" id="dateModalLabel">选择日期</h5>
                    <button class="modal-close" data-dismiss="modal" aria-label="Close">×</button>
                </div>
                <div class="modal-body">
                    <div class="date-picker-container">
                        <div class="date-quick-options">
                            <button type="button" class="date-quick-btn" data-days="0">今天</button>
                            <button type="button" class="date-quick-btn" data-days="-1">昨天</button>
                            <button type="button" class="date-quick-btn" data-days="-2">前天</button>
                        </div>
                        <input type="date" class="form-control" id="date-picker" value="{{ $transaction_date ?: date('Y-m-d') }}">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirm-date">确定</button>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('styles')
<style>
/* 记账表单样式 */
.app-container {
    padding-bottom: 0px;
}
.form-container {
    background: white;
    border-radius: 20px 20px 0 0;
    min-height: calc(100vh - 120px);
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #2d3748;
}

.form-input {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    font-size: 16px;
    transition: all 0.3s ease;
    background: #f8f9fa;
}

.form-input:focus {
    outline: none;
    border-color: #667eea;
    background: white;
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 输入区域 */
.input-area {
    display: flex;
    align-items: center;
    background: white;
    padding: 15px 20px;
    margin-bottom: 10px;
    border-radius: 15px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.description-input {
    font-size: 15px;
    color: #4a5568;
    transition: all 0.3s ease;
    border: none;
    outline: none;
    flex-grow: 1;
    background: transparent;
}

.description-input::placeholder {
    color: #a0aec0;
}

.amount-display {
    font-size: 20px;
    font-weight: 700;
    color: #38a169;
    background: linear-gradient(135deg, #51cf66 0%, #38a169 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    padding: 0 15px;
}

.receipt-upload {
    background: linear-gradient(135deg, #f8f9fa 0%, #e2e8f0 100%);
    width: 40px;
    height: 40px;
    border: none;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    color: #4a5568;
    font-size: 18px;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
}

.receipt-upload:hover {
    transform: translateY(-2px) scale(1.05);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    color: #38a169;
}

/* 计算器 */
.calculator {
    /*background: linear-gradient(135deg, rgba(240, 255, 244, 0.95) 0%, rgba(226, 242, 228, 0.95) 100%);*/
    /*backdrop-filter: blur(10px);*/
    /*border-radius: 20px 20px 0 0;*/
    /*padding: 25px 20px;*/
    /*box-shadow: 0 -4px 20px rgba(0,0,0,0.08);*/
    margin-top: auto;
}

.calculator-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 12px;
}

.calculator-grid .equals {
    grid-column: span 2;
}

.calculator-btn {
    height: 60px;
    border: none;
    border-radius: 16px;
    font-size: 20px;
    font-weight: 600;
    background: white;
    color: #4a5568;
    box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    transition: all 0.3s ease;
}

.calculator-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.calculator-btn:active {
    transform: translateY(1px);
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.calculator-btn.btn-clicked {
    animation: buttonClick 0.15s ease-in-out;
}

@keyframes buttonClick {
    0% { transform: scale(1); }
    50% { transform: scale(0.95); }
    100% { transform: scale(1); }
}

.calculator-btn.operator {
    background: linear-gradient(135deg, #f0fff4 0%, #dcfce7 100%);
    color: #38a169;
    font-weight: 700;
}

.calculator-btn.date {
    background: linear-gradient(135deg, #e6fffa 0%, #d0f7ef 100%);
    color: #319795;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(49, 151, 149, 0.2);
}

.calculator-btn.date:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 18px rgba(49, 151, 149, 0.3);
}

.calculator-btn.equals {
    background: linear-gradient(135deg, #51cf66 0%, #38a169 100%);
    color: white;
    font-weight: 700;
    box-shadow: 0 4px 15px rgba(56, 161, 105, 0.3);
}

.calculator-btn.equals:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(56, 161, 105, 0.4);
}

.calculator-btn#cancel-btn {
    background: linear-gradient(135deg, #edf2f7 0%, #cbd5e0 100%);
    color: #4a5568;
    font-weight: 600;
    box-shadow: 0 4px 12px rgba(74, 85, 104, 0.2);
}

.calculator-btn#cancel-btn:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 18px rgba(74, 85, 104, 0.3);
}

.amount-display {
    background: linear-gradient(135deg, #ff6b6b 0%, #e53e3e 100%);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}

.receipt-upload:hover {
    color: #e53e3e;
}

/* 日期选择器样式 */
.date-picker-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.date-quick-options {
    display: flex;
    justify-content: space-between;
    gap: 10px;
    margin-bottom: 10px;
}

.date-quick-btn {
    flex: 1;
    background: linear-gradient(135deg, #f0fff4 0%, #dcfce7 100%);
    border: none;
    border-radius: 12px;
    padding: 10px 0;
    font-weight: 600;
    color: #38a169;
    transition: all 0.3s ease;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.date-quick-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(56, 161, 105, 0.2);
}

.btn-primary {
    background: linear-gradient(135deg, #51cf66 0%, #38a169 100%);
    border: none;
    border-radius: 12px;
    padding: 10px 25px;
    font-weight: 600;
    box-shadow: 0 4px 15px rgba(56, 161, 105, 0.3);
    transition: all 0.3s ease;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(56, 161, 105, 0.4);
}

</style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    // 初始化变量
    let selectedCategoryId = {{ $category ?: 'null' }};
    let selectedSubCategoryId = {{ $sub_category ?: 'null' }};
    let selectedCategoryId_ori = selectedCategoryId;
    let selectedSubCategoryId_ori = selectedSubCategoryId;
    let currentAmount = '{{ $amount ?: "0" }}';
    let currentOperator = null;
    let previousValue = null;
    let newInput = true;
    let calculationInProgress = false;

    // 更新金额显示
    function updateAmountDisplay() {
        $('#amount-display').text(parseFloat(currentAmount).toFixed(2));
        $('#amount').val(currentAmount);
    }

    // 更新日期显示
    function updateDateDisplay() {
        const date = $('#record-date').val();
        const displayDate = new Date(date);
        const month = displayDate.getMonth() + 1;
        const day = displayDate.getDate();
        $('#date-display').text(`${month}.${day}`);
    }

    // 切换收入支出标签
    const expenseTab = $('#expense-tab');
    const incomeTab = $('#income-tab');
    const expenseCategories = $('#expense-categories');
    const incomeCategories = $('#income-categories');

    function switchToExpense() {
        expenseTab.addClass('active');
        incomeTab.removeClass('active');
        expenseCategories.show();
        incomeCategories.hide();
        $('#transaction-type').val('expense');
        $('#record-form-title').text('记录支出');
        hideAllSubcategories();

        // 选中第一个支出分类
        const firstExpenseCategory = expenseCategories.find('.category-item').first();
        if (firstExpenseCategory.length) {
            expenseCategories.find('.category-item').removeClass('active');
            firstExpenseCategory.addClass('active');
            selectedCategoryId = firstExpenseCategory.data('category-id');
            selectedSubCategoryId = null;

            // 显示对应的二级分类
            selectSubCategoryAuto('expense', 0);
        }
    }

    function switchToIncome() {
        incomeTab.addClass('active');
        expenseTab.removeClass('active');
        incomeCategories.show();
        expenseCategories.hide();
        $('#transaction-type').val('income');
        $('#record-form-title').text('记录收入');
        hideAllSubcategories();

        // 选中第一个收入分类
        const firstIncomeCategory = incomeCategories.find('.category-item').first();
        if (firstIncomeCategory.length) {
            incomeCategories.find('.category-item').removeClass('active');
            firstIncomeCategory.addClass('active');
            selectedCategoryId = firstIncomeCategory.data('category-id');
            selectedSubCategoryId = null;

            // 显示对应的二级分类
            selectSubCategoryAuto('income', 0);
        }
    }

    function selectSubCategoryAuto(type, sub_id = 0) {
        const subcategorySelector = $(`#subcategory-${type}-${selectedCategoryId}`);
        subcategorySelector.show();
        var firstSubCategory;
        if (!sub_id) {
            if (selectedSubCategoryId_ori && selectedCategoryId === selectedCategoryId_ori) sub_id = selectedSubCategoryId_ori;
        }
        if (sub_id) {
            firstSubCategory = subcategorySelector.find(`.subcategory-item[data-subcategory-id="${sub_id}"]`);
        }
        if (!firstSubCategory || !firstSubCategory.length) {
            firstSubCategory = subcategorySelector.find('.subcategory-item').first();
        }

        if (firstSubCategory.length) {
            subcategorySelector.find('.subcategory-item').removeClass('active');
            firstSubCategory.addClass('active');
            selectedSubCategoryId = firstSubCategory.data('subcategory-id');
            showSelectInfo();
        }
    }

    function showSelectInfo() {
        // 更新已选分类信息
        const categoryName = $('.category-item.active').data('category');
        const subcategoryName = $('.subcategory-item.active').data('subcategory');
        if (categoryName && subcategoryName) {
            $('#category-selected-info').text(`已选: ${categoryName} - ${subcategoryName}`).show();
        }
    }

    expenseTab.click(switchToExpense);
    incomeTab.click(switchToIncome);

    // 隐藏所有二级分类
    function hideAllSubcategories() {
        $('.subcategory-selector').hide();
        $('.subcategory-item').removeClass('active');
        $('#category-selected-info').hide();
    }

    // 一级分类选择
    $('.category-item').click(function() {
        const parent = $(this).parent();
        parent.find('.category-item').removeClass('active');
        $(this).addClass('active');

        selectedCategoryId = $(this).data('category-id');
        selectedSubCategoryId = null;

        hideAllSubcategories();

        // 显示对应的二级分类
        selectSubCategoryAuto($(this).data('type'), selectedSubCategoryId);
    });

    // 二级分类选择
    $('.subcategory-item').click(function() {
        const parent = $(this).parent();
        parent.find('.subcategory-item').removeClass('active');
        $(this).addClass('active');

        selectedSubCategoryId = $(this).data('subcategory-id');

        // 更新已选分类信息
        showSelectInfo();
    });

    // 计算器功能
    $('.calculator-btn').click(function() {
        const value = $(this).data('value');

        // 添加按钮点击动画效果
        $(this).addClass('btn-clicked');
        setTimeout(() => {
            $(this).removeClass('btn-clicked');
        }, 150);

        if (value !== undefined) {
            handleNumberOrOperator(value);
        }
    });

    // 处理数字或运算符输入
    function handleNumberOrOperator(value) {
        // 处理数字和小数点
        currentAmount = currentAmount.toString();
        if (!isNaN(value) || value === '.') {
            if (newInput) {
                currentAmount = value === '.' ? '0.' : value;
                newInput = false;
            } else {
                // 确保只有一个小数点
                if (value === '.' && currentAmount.includes('.')) {
                    return;
                }
                // 限制小数点后两位
                if (currentAmount.includes('.') && currentAmount.split('.')[1].length >= 2 && value !== '.') {
                    return;
                }
                currentAmount += value;
            }
            updateAmountDisplay();
        }
        // 处理运算符
        else if (value === '+' || value === '-') {
            if (calculationInProgress) {
                // 如果已经有一个计算在进行中，先计算结果
                calculate();
            }
            previousValue = parseFloat(currentAmount);
            currentOperator = value;
            newInput = true;
            calculationInProgress = true;
        }

        // 确保计算器按钮在任何情况下都能响应
        $('.calculator-btn').removeClass('btn-clicked');

    }

    // 计算结果
    function calculate() {
        if (!calculationInProgress) return;

        const currentVal = parseFloat(currentAmount);
        let result;

        if (currentOperator === '+') {
            result = previousValue + currentVal;
        } else if (currentOperator === '-') {
            result = previousValue - currentVal;
        }

        // 确保结果为正数
        result = Math.max(0, result);

        // 限制小数点后两位
        currentAmount = result.toString();
        updateAmountDisplay();

        // 重置计算状态
        previousValue = null;
        currentOperator = null;
        calculationInProgress = false;
        newInput = true;
    }

    // 删除按钮功能
    $('#delete-btn').click(function() {
        if (currentAmount.length > 1) {
            currentAmount = currentAmount.slice(0, -1);
        } else {
            currentAmount = '0';
        }
        updateAmountDisplay();
        newInput = false;
    });

    // 日期选择按钮点击事件
    $('#date-btn').click(function() {
        $('#dateModal').modal('show');
    });

    // 确认日期按钮点击事件
    $('#confirm-date').click(function() {
        const selectedDate = $('#date-picker').val();
        $('#record-date').val(selectedDate);
        updateDateDisplay();
        $('#dateModal').modal('hide');
    });

    // 日期快速选择按钮点击事件
    $('.date-quick-btn').click(function() {
        const days = parseInt($(this).data('days'));
        const today = new Date();
        const selectedDate = new Date(today);
        selectedDate.setDate(today.getDate() + days);

        const formattedDate = selectedDate.toISOString().split('T')[0];
        $('#date-picker').val(formattedDate);
    });

    // 取消按钮和关闭按钮点击事件
    $('.btn-secondary, .close').click(function() {
        $('#dateModal').modal('hide');
    });

    // 收据上传按钮
    $('#receipt-upload').click(function() {
        // 这里可以添加上传收据的功能
        showInfo('收据上传功能即将上线');
    });

    // 返回按钮功能
    $('#cancel-btn').click(function() {
        window.location.href = '/';
    });

    // 初始化默认选择
    const initialType = $('#transaction-type').val();
    var firstCategory = null;
    if (initialType === 'expense') {
        if (!selectedCategoryId) {
            firstCategory = expenseCategories.find('.category-item').first();
            if (firstCategory.length) {
                selectedCategoryId = firstCategory.data('category-id');
            }
            selectedSubCategoryId = 0;
        } else {
            firstCategory = expenseCategories.find(`.category-item[data-category-id="${selectedCategoryId}"]`);
            if (!firstCategory.length) {
                firstCategory = expenseCategories.find('.category-item').first();
                if (firstCategory.length) {
                    selectedCategoryId = firstCategory.data('category-id');
                }
            }
        }
        expenseCategories.find('.category-item').removeClass('active');
        firstCategory.addClass('active');
        selectSubCategoryAuto('expense', selectedSubCategoryId);
    } else {
        if (!selectedCategoryId) {
            firstCategory = incomeCategories.find('.category-item').first();
            if (firstCategory.length) {
                selectedCategoryId = firstCategory.data('category-id');
            }
            selectedSubCategoryId = 0;
        } else {
            firstCategory = incomeCategories.find(`.category-item[data-category-id="${selectedCategoryId}"]`);
            if (!firstCategory.length) {
                firstCategory = incomeCategories.find('.category-item').first();
                if (firstCategory.length) {
                    selectedCategoryId = firstCategory.data('category-id');
                }
            }
        }
        incomeCategories.find('.category-item').removeClass('active');
        firstCategory.addClass('active');
        selectSubCategoryAuto('income', selectedSubCategoryId);
    }

    // 提交记账表单
    $('#saveBtn').click(function(e) {
        e.preventDefault();

        // 添加按钮点击动画效果
        $(this).addClass('btn-clicked');
        setTimeout(() => {
            $(this).removeClass('btn-clicked');
        }, 150);

        // 如果有计算在进行中，先计算结果
        if (calculationInProgress) {
            calculate();
        }

        if (!selectedCategoryId || !selectedSubCategoryId) {
            showError('请选择分类');
            return;
        }

        if (parseFloat(currentAmount) <= 0) {
            showError('请输入有效金额');
            return;
        }

        const formData = {
            _token: $('input[name="_token"]').val(),
            type: $('#transaction-type').val(),
            amount: currentAmount,
            category_id: selectedCategoryId,
            sub_category_id: selectedSubCategoryId,
            transaction_date: $('#record-date').val(),
            description: $('#record-note').val(),
            ai_key: '{{ $ai_key }}',
            ai_edit: 1,
        };

        $.ajax({
            url: '{{ route("transaction.store") }}',
            method: 'POST',
            data: formData,
            success: function(response) {
                if (response.success) {
                    showSuccess('记账成功！');
                    setTimeout(() => {
                        window.location.href = '{{ route("home") }}';
                    }, 1000);
                } else {
                    showError(response.message || '记账失败');
                }
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    let errorMessage = '验证失败：\n';
                    for (let field in errors) {
                        errorMessage += errors[field].join('\n') + '\n';
                    }
                    showError(errorMessage);
                } else {
                    showError('记账失败，请重试');
                }
            }
        });
    });

    // 初始化显示
    updateAmountDisplay();
    updateDateDisplay();
});
</script>
@endpush
